package com.h3bpm.kumhosunny.purchase.controller;
import OThinker.Common.Organization.Models.Unit;
import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import OThinker.H3.Portal.webservices.Entity.DataItemParam;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.h3bpm.base.util.AppUtility;
import com.h3bpm.kumhosunny.common.utils.JavaNetUrlRestFulClient;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import sun.misc.BASE64Encoder;

/**
 * @author zhangpf
 * @date 2019/8/13
 * @description test
 */

@Controller
@RequestMapping("/Portal/SchemeEvaluationChild")
public class SchemeEvaluation extends ControllerBase{
    private static final Logger LOGGER =
            LoggerFactory.getLogger(SchemeEvaluation.class);
    @Override
    public String getFunctionCode() {
        return null;
    }

    @RequestMapping("/StartSchemeEvaluationChild")
    @ResponseBody
   public String startSchemeEvaluationChildFlow (String instanceId){

       try {
           InstanceData instanceData = new InstanceData(AppUtility.getEngine(), instanceId, User.AdministratorID);
           HashMap<String, Object> procurementValues = instanceData.getBizObject().getValueTable();
           //处理解析子流程数据
           Map<String , List<DataItemParam>>  mapData = schemeEvaluationChildData (instanceData,procurementValues);
           //循环发起子流程
           for(String userCode : mapData.keySet()){
               String result = JavaNetUrlRestFulClient.startInstance("H3","Authine","schemeEvaluationChild",userCode ,"false",mapData.get(userCode));
               ObjectMapper mapper = new ObjectMapper();
               JavaType javaType = mapper.getTypeFactory()
                       .constructParametricType(Map.class, String.class, Object.class);
               Map<String, Object> resultMap = mapper.readValue(result, javaType);
               if (!"0".equals(resultMap.get("code").toString())){
                   LOGGER.error("流程实例启动失败！ 员工objectid == "+userCode);
               }else{

               }
           }
       } catch (Exception e) {
           e.printStackTrace();

       }
       return "OK";
   }

   public  Map<String ,List<DataItemParam>> schemeEvaluationChildData ( InstanceData instanceData,Map<String, Object> schemeEvaluationData){
       Map<String ,List<DataItemParam>> listData = new HashMap<String , List<DataItemParam>>(3);
       SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       String projectLeaderTrue ="";
       try {
           BizObject[]  bizObjects= null;

           BizObject[]  projectGroupMessage= null;

           if(schemeEvaluationData.get("supplierInformation")!=null){

               bizObjects= (BizObject[]) schemeEvaluationData.get("supplierInformation");

           }
           if(schemeEvaluationData.get("projectGroupMessage")!=null){

               projectGroupMessage= (BizObject[]) schemeEvaluationData.get("projectGroupMessage");

           }

           //把所有组员加到集合中
           List<String> participant =new ArrayList<String>();
           if(projectGroupMessage!=null) {
               for (BizObject projectObj : projectGroupMessage) {
                   Map<String, Object> zbValueTable = projectObj.getValueTable();
                   String userId = zbValueTable.get("groupMembers").toString();
                   participant.add(userId);
               }
           }
           //把组长加到集合中
           participant.add(schemeEvaluationData.get("projectLeaderTrue").toString());
           projectLeaderTrue=schemeEvaluationData.get("projectLeaderTrue").toString();
           String projectName=schemeEvaluationData.get("projectName").toString();
           String projectCode=schemeEvaluationData.get("projectNumber").toString();

           for(String participantValue : participant) {
               JSONArray schemeEvaluationChild = new JSONArray();
               List<DataItemParam> list = new ArrayList<>();
               list.add(new DataItemParam("ModifiedBy", participantValue));
               list.add(new DataItemParam("CreatedBy", participantValue));
               User user = (User) getEngine().getOrganization().GetUnit(participantValue);
               Unit  unit = getEngine().getOrganization().GetUnit(user.getParentID());
               list.add(new DataItemParam("CreatedByParentId", unit.getObjectID()));
               list.add(new DataItemParam("OwnerId", participantValue));
               String objectId = UUID.randomUUID().toString();
               list.add(new DataItemParam("ObjectID",objectId));
               list.add(new DataItemParam("ParentObjectID",schemeEvaluationData.get("ObjectID").toString()));
               list.add(new DataItemParam("CreatedTime", simpleDateFormat.format(new Date())));
               list.add(new DataItemParam("ModifiedTime",  simpleDateFormat.format(new Date())));
        if(bizObjects!=null) {
            for (BizObject bizObj : bizObjects) {
                JSONObject subject = new JSONObject(true);
                Map<String, Object> zbValueTable = bizObj.getValueTable();
                String dimensionalityValue = zbValueTable.get("dimensionality").toString();
                String[] dimensionalityValues = dimensionalityValue.split(";");
                String tableId = UUID.randomUUID().toString();
                subject.put("tableID", tableId);
                subject.put("subjectName", zbValueTable.get("subject").toString());
                subject.put("supplierA", zbValueTable.get("supplierA").toString());
                subject.put("supplierB", zbValueTable.get("supplierB").toString());
                subject.put("supplierC", zbValueTable.get("supplierC").toString());
                subject.put("supplierD", zbValueTable.get("supplierD").toString());
                JSONArray subjectTable = new JSONArray();
                for (int i = 0; i < dimensionalityValues.length; i++) {
                    JSONObject subjectRow = new JSONObject(true);
                    subjectRow.put("dimension", dimensionalityValues[i]);
                    subjectTable.add(subjectRow);
                }
                subject.put("subjectTable", subjectTable);
                schemeEvaluationChild.add(subject);
            }
        }
           String jsonArray = schemeEvaluationChild.toJSONString();
           BASE64Encoder encoder = new BASE64Encoder();
           String encodejsonArray = encoder.encode(jsonArray.getBytes());
           list.add(new DataItemParam("content",encodejsonArray));
           list.add(new DataItemParam("projectName",projectName));
           list.add(new DataItemParam("projectCode",projectCode));
           list.add(new DataItemParam("projectLeaderTrue",projectLeaderTrue));
           list.add(new DataItemParam("parentInstanceId",instanceData.getInstanceId()));
          Unit unitPerson = getEngine().getOrganization().GetUnit(instanceData.getBizObject().getCreatedBy());
           list.add(new DataItemParam("parentProcessOrg",unitPerson.getName()));
           listData.put(user.getCode(),list);
       }
       } catch ( Exception e) {
           e.printStackTrace();
       }
       return listData;
   }



    /**
     * 解析数据库中xml
     * @param xml
     * @return
     */
   public List<String> analysisXml(String xml){

     List<String> valueList= new ArrayList<String>();
       try {
           StringReader sr = new StringReader(xml);
           InputSource is = new InputSource(sr);
           String parseXmlStr = null;
           int count = 0;
           DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
           // step 2:获得具体的dom解析器
           DocumentBuilder builder = null;
           builder = factory.newDocumentBuilder();
           Document document = builder.parse(is);
           //获取mxGraphModel属性
           Element mxGraphModel = document.getDocumentElement();
           //获取root节点
           NodeList root = mxGraphModel.getChildNodes();
           for (int i=0 ; i<root.getLength();i++){
               Node str =root.item(i);
               NodeList mxCell = str.getChildNodes();
               for(int j = 0; j < mxCell.getLength(); j++) {
                   Object element =   mxCell.item(j);
                   valueList.add(((Node) element).getNodeValue());
               }
           }
       } catch ( Exception e) {
           e.printStackTrace();
       }
     return valueList;

   }

}
